package org.vectrics.recruiter.struts.tag;

/**
 * Title: Web Site Description: Copyright: Copyright (c) 2001 Company: vectrics
 * 
 * @author Mike Moore
 * @version 1.0
 */

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeSet;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import org.apache.ecs.html.A;
import org.apache.log4j.Category;
import org.vectrics.SystemException;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.html.TextHelper;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.location.Location;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.job.Job;
import org.vectrics.recruiter.job.JobSearchRating;
import org.vectrics.struts.VectricsTagSupport;

public class JobsFoundTag extends VectricsTagSupport {

    private static final long serialVersionUID = -2950074941615916557L;

    private static Category log = Category.getInstance(JobsFoundTag.class);

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

    private String searchPhrase = "";

    private String function = "";

    private String location = "";

    private String time = "";

    public JobsFoundTag() {
        super();
    }

    /*
     * public void setJobList(Collection jobList) { sortedJobs.clear();
     * sortedJobs.addAll(jobList); }
     * 
     * public Collection getJobList() { return(sortedJobs); }
     */
    // public String getSearchPhrase() {
    // return(this.searchPhrase);
    // }
    //
    // public void setSearchPhrase(String phrase) {
    // this.searchPhrase = phrase;
    // }

    public String getFunction() {
        return function;
    }

    public void setFunction(final String function) {
        this.function = function;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(final String location) {
        this.location = location;
    }

    public String getTime() {
        return time;
    }

    public void setTime(final String time) {
        this.time = time;
    }

    @Override
    public String makeStartTag() {
        Table mainTable = new Table();
        try {
            log.debug("doStartTag() - called");
            ServletRequest servletRequest = super.pageContext.getRequest();
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpSession session = super.pageContext.getSession();
            String contextRoot = request.getContextPath();

            Row mainRow = mainTable.addRow();
            Cell mainCell = mainRow.addCell();

            String functionId = getFunction();
            // String searchWords = getSearchPhrase();

            String locationId = getLocation();
            String timeParam = getTime();
            String thisUrl = request.getRequestURI() + "?" + request.getQueryString();
            String prevParam = request.getParameter("prev");

            long startTime = 0;
            if (timeParam != null) {
                try {
                    startTime = Long.parseLong(timeParam);
                } catch (Exception ex) {
                    log.debug("doRender() - illegal value for time param value = " + timeParam);
                }

            }

            log.debug("doPerform() submit button pressed - saving..");

            TreeSet sortedJobs = (TreeSet) request.getSession().getAttribute("last_job_search");
            if (sortedJobs == null)
                throw new JspException(
                        "Session did not have 'last_job_search' set.  Make sure JobSearchAction is invoked for request.");

            Collection jobIds = null;
            sortedJobs = (TreeSet) session.getAttribute("job_list");
            if (sortedJobs == null)
                throw new JspException(
                        "Could not find job_list attached to session.  Make sure JobSearchAction is called before this tag is rendered.");

            Iterator jobIdIter = sortedJobs.iterator();
            if (jobIdIter.hasNext()) {
                BorderTable table = new BorderTable();
                mainCell.addElement(table);
                table.setWidth(600);

                // Make header
                Row hdrRow = table.addRow();
                hdrRow.setDefaultBgImage(getContextPath() + "/site-graphics/tbl_hdr.gif");

                Cell hdrCell = hdrRow.addCell();
                // hdrCell.setClass("tableHdrBg");
                hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Date Posted"));
                hdrCell = hdrRow.addCell();
                // hdrCell.setClass("tableHdrBg");
                hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Job Title"));
                hdrCell = hdrRow.addCell();
                // hdrCell.setClass("tableHdrBg");
                hdrCell.addElement(TextHelper.getFont("tableHdrFont", "CompanyLocation"));

                while (jobIdIter.hasNext()) {
                    JobSearchRating rating = (JobSearchRating) jobIdIter.next();
                    Long jobIdLong = null;
                    if (rating.getJobId() != null) {
                        jobIdLong = rating.getJobId();
                    }
                    Job job = RecruitServiceLocator.getJobProvider().findJob(jobIdLong);

                    Row row = table.addRow();
                    Cell cell = row.addCell();

                    cell.addElement(TextHelper.getFont("subFont", dateFormat.format(job.getDatePosted())));

                    cell = row.addCell();
                    A jobDescLink = new A();
                    jobDescLink.setClass("lnkJobList");
                    jobDescLink.setHref(contextRoot + "/public/" + ThreadProperties.getUriDomainId()
                            + "/job/job_view.do?jobId=" + job.getId());
                    jobDescLink.addElement(job.getTitle());
                    cell.addElement(jobDescLink);

                    Location location = null;
                    try {
                        location = job.getLocation();
                    } catch (Exception ex) {
                        throw new JspException(ex);
                    }
                    cell = row.addCell();
                    if (location != null) {
                        cell.addElement(TextHelper.getFont("subFont", "" + location.getName()));
                    }
                }
            } else {
                mainCell.addElement("<h3><i>No Jobs Found that Matched Your Search Criteria</i></h3>");
            }

            JspWriter writer = pageContext.getOut();
            try {
                writer.print(mainTable.toString());
            } catch (IOException ex) {
                throw new JspException("IOException attempting to write tag to output. " + ex.getMessage());
            }
        } catch (Exception ex) {
            log.error("Exception in doStartTag()", ex);
            throw new SystemException("Exception in doStartTag()", ex);
        }
        return mainTable.toString();
    }

}
